package com.leruan.aasimp.action.forum;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.leruan.aasimp.entity.Forumuser;
import com.leruan.aasimp.entitydto.StaticStrings;
import com.leruan.aasimp.service.ForumUserService;
import com.leruan.aasimp.util.DateUtils;
import com.leruan.aasimp.util.StringUtil;
import com.leruan.aasimp.util.Validators;
import com.opensymphony.xwork2.ActionSupport;

public class RegisterAction extends ActionSupport {

    /**
     * 
     */
    private static final long serialVersionUID = -3002191296807417454L;
    @Resource
    private ForumUserService forumUserService;
    public final String JPG = "jpg";
    public final String GIF = "gif";
    public final String JPEG = "jpeg";

    public FileItem fileItem;
    private String errorMessage;
    private String actionMessage;

    public String toRegister() {
        return "success";
    }

    public String showPicture() {
        return "success";
    }

    public String iconUpload() {
        HttpServletRequest request = ServletActionContext.getRequest();
        DiskFileItemFactory f = new DiskFileItemFactory();// 磁盘对象
        f.setRepository(new File("d:/a")); // 设置临时目录
        f.setSizeThreshold(1024 * 8); // 8k的缓冲区,文件大于8K则保存到临时目录
        ServletFileUpload upload = new ServletFileUpload(f);// 声明解析request的对象
        upload.setHeaderEncoding("UTF-8"); // 处理文件名中文
        upload.setFileSizeMax(1024 * 1024 * 5);// 设置每个文件最大为5M
        upload.setSizeMax(1024 * 1024 * 10);// 一共最多能上传10M
        String absolutePath = "";// 文件存放路径
        String absoluteRootPath = StaticStrings.FILEPATH + "img" + File.separator + "icon" + File.separator;
        String curDate = DateUtils.date2String(new Date(), "yyyyMMdd");
        absolutePath = absoluteRootPath + curDate;
        String path = absolutePath;// 获取文件要保存的目录
        try {
            List<FileItem> list = upload.parseRequest(request);// 解析
            for (FileItem ff : list) {
                if (ff.isFormField()) {
                    String ds = ff.getString("UTF-8");// 处理中文
                    System.err.println("说明是:" + ds);
                }
                else {
                    String ss = ff.getName();
                    ss = ss.substring(ss.lastIndexOf("\\") + 1);// 解析文件名
                    FileUtils.copyInputStreamToFile( // 直接使用commons.io.FileUtils
                            ff.getInputStream(), new File(path + "/" + ss));
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        // HttpServletRequest request = ServletActionContext.getRequest();
        // if (fileItem == null || fileItem.getSize() == 0) {
        // errorMessage = "请选择要上传的图片源文件";
        // request.setAttribute("errorMessage", errorMessage);
        // return "input";
        // }
        // if (!FileUtils.getExtension(fileItem.getName()).equalsIgnoreCase(JPG)
        // && !FileUtils.getExtension(fileItem.getName()).equalsIgnoreCase(GIF)
        // && !FileUtils.getExtension(fileItem.getName()).equalsIgnoreCase(JPEG)) {
        // errorMessage = "请上传格式为JPG、JPEG、GIF的图片源文件";
        // request.setAttribute("errorMessage", errorMessage);
        // return "input";
        // }
        // if (fileItem.getSize() > 200 * 100) {
        // errorMessage = "对不起，上传图片大小不能超过200*100";
        // request.setAttribute("errorMessage", errorMessage);
        // return "input";
        // }
        // String absolutePath = "";// 文件存放路径
        // String absoluteRootPath = StaticStrings.FILEPATH + "img" + File.separator + "homepage" + File.separator;
        // String curDate = DateUtils.date2String(new Date(), "yyyyMMdd");
        // absolutePath = absoluteRootPath + curDate;
        //
        // File d = new File(absolutePath);
        // if (!d.exists()) {
        // d.mkdirs();
        // }
        // String uuidHex = StringUtil.getUUID();
        // String fileName = uuidHex + "." + FileUtils.getExtension(fileItem.getName());
        // String imageUrl = curDate + "/" + fileName;
        // fileName = absolutePath + "/" + fileName;
        // File file = new File(fileName);
        // try {
        // fileItem.write(file);
        // StringBuffer stringBuffer = new StringBuffer();
        // stringBuffer.append("parent.readPictureUrl(\"").append("img/").append("homepage/").append(imageUrl).append(
        // "\");\n");
        // actionMessage = stringBuffer.toString();
        // request.setAttribute("actionMessage", actionMessage);
        return "success";
        // }
        // catch (Exception e) {
        // fileItem = null;
        // errorMessage = "原文件上传失败";
        // request.setAttribute("errorMessage", errorMessage);
        // return "input";
        // }
    }

    public String register() throws UnsupportedEncodingException {
        HttpServletRequest request = ServletActionContext.getRequest();
        String userId = StringUtil.getUUID();
        String username = request.getParameter("username");
        String nickname = request.getParameter("nickname");
        Long userType = Long.parseLong(request.getParameter("userType"));
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String sex = request.getParameter("sex");
        String birthday = request.getParameter("birthday");
        String selfIntroduction = request.getParameter("selfIntroduction");
        String isShowEmailStr = request.getParameter("isShowEmail");
        Long isShowEmail;
        if (Validators.isEmpty(isShowEmailStr)) {
            isShowEmail = 0l;
        }
        else {
            isShowEmail = Long.parseLong(request.getParameter("isShowEmail"));
        }
        Date registerDate = new Date();
        Forumuser forumuser = new Forumuser(userId, username, nickname, DateUtils.string2Date(birthday), password, 1l,
                email, 0l, 0l, "", sex, selfIntroduction, registerDate, userType, isShowEmail, "");
        validateParameter(forumuser);
        if (hasErrors()) {
            return "wrong";
        }
        forumUserService.saveForumUser(forumuser);
        return "success";
    }

    private void validateParameter(Forumuser forumuser) {
        Forumuser forumuser2;
        if (Validators.isEmpty(forumuser.getUsername())) {
            addActionError("用户名不能为空");
        }
        forumuser2 = forumUserService.getForumUserByUsername(forumuser.getUsername());
        if (null != forumuser2) {
            addActionError("用户名已存在，请重新取一个");
        }
        if (Validators.isEmpty(forumuser.getNickname())) {
            addActionError("昵称不能为空");
        }
        if (Validators.isEmpty(forumuser.getPassword())) {
            addActionError("密码不能为空");
        }
        if (Validators.isEmpty(forumuser.getEmail())) {
            addActionError("Email不能为空");
        }
    }

    public ForumUserService getForumUserService() {
        return forumUserService;
    }

    public void setForumUserService(ForumUserService forumUserService) {
        this.forumUserService = forumUserService;
    }

    public FileItem getFileItem() {
        return fileItem;
    }

    public void setFileItem(FileItem fileItem) {
        this.fileItem = fileItem;
    }

}
